<template>
  <div class="main_box" v-loading="pageLoading">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="filters" class="demo-form-inline" ref="searchForm">
            <el-form-item prop="queryCode">
              <el-input v-model="filters.queryCode" clearable placeholder="平台/医检条码号"></el-input>
            </el-form-item>
            <!--<el-form-item prop="searchCode">
              <el-input v-model="filters.searchCode" clearable placeholder="查询号"></el-input>
            </el-form-item>-->
            <el-form-item prop="itemName">
              <el-input v-model="filters.itemName" clearable placeholder="送检项目"></el-input>
            </el-form-item>
            <el-form-item prop="patientQuery">
              <el-input v-model="filters.patientQuery" clearable placeholder="患者姓名/手机/身份证"></el-input>
            </el-form-item>
            <el-form-item prop="userId" v-if="userRole !== 2">
              <el-select v-model="filters.userId" :clearable="true" filterable placeholder="收样员姓名">
                <el-option v-for="item in collectList" :key="item.value" :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="hospitalId" v-if="userRole !== 2">
              <el-select v-model="filters.hospitalId" @change="listOffice" filterable :clearable="true"
                         placeholder="医院名称">
                <el-option v-for="item in hospitalList" :key="item.value" :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="officeId">
              <el-select v-model="filters.officeId" @change="listDoctor" filterable :clearable="true"
                         placeholder="科室名称">
                <el-option v-for="item in officeList" :key="item.value" :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="doctorId" v-if="userRole !== 2">
              <el-select v-model="filters.doctorId" filterable :clearable="true" placeholder="医生名称">
                <el-option v-for="item in doctorList" :key="item.value" :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="institutionId" v-if="userRole !== 3">
              <el-select v-model="filters.institutionId" filterable :clearable="true" placeholder="医检名称">
                <el-option v-for="item in institutionList" :key="item.value" :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <!--<InstitutionSelect @institutionId="getInstitutionId" :site="2"></InstitutionSelect>-->
            <el-form-item prop="reportState" v-if="userRole !== 2 && userRole !== 3">
              <el-select v-model="filters.reportState" :clearable="true" placeholder="报告单状态">
                <el-option v-for="item in reviewStatue" :key="item.value" :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="resultState">
              <el-select v-model="filters.resultState" :clearable="true" placeholder="结果状态">
                <el-option v-for="item in resultStatue" :key="item.value" :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="printState">
              <el-select v-model="filters.printState" :clearable="true" placeholder="打印状态">
                <el-option v-for="item in agenciesStatue" :key="item.value" :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <!--<br/><span>送检时间：</span>-->
            <el-form-item prop="date">
              <el-date-picker
                  v-model="filters.date"
                  :clearable="true"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="送检开始日期"
                  end-placeholder="送检结束日期"
                  :default-time="['00:00:00', '23:59:59']"
              ></el-date-picker>
            </el-form-item>
            <el-form-item prop="abnormalState" v-if="userRole === 1">
              <el-select v-model="filters.abnormalState" :clearable="true" placeholder="异常状态">
                <el-option v-for="item in abnormalStatue" :key="item.value" :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item prop="applyId">
              <el-input v-model="filters.applyId" clearable placeholder="采样编号"></el-input>
            </el-form-item>
            <el-form-item prop="state" v-has="permissionResume">
              <el-select v-model="filters.state" :clearable="true" placeholder="状态">
                <el-option key="1" label="正常" value="1"></el-option>
                <el-option key="-1" label="已删除" value="-1"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="onSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="init" size="mini"></el-button>
          </el-tooltip>
          <div>
            <el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAdd()"
                       size="mini"> 新增
            </el-button>
            <el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAdd(true)"
                       size="mini"> 新增 - 新版报告单
            </el-button>
            <el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAddBatch()"
                       size="mini"> 批量新增
            </el-button>
            <!-- <el-button
              type="primary"
              plain
              icon="fa fa-plus"
              v-has="permissionAdd"
              @click="handleBatchImport()"
              size="mini"
            >
              批量导入</el-button
            > -->
            <el-button size="mini" plain type="danger" icon="el-icon-receiving" v-has="permissionMergeUpload"
                       @click="handleClickMergeUpload">合并上传
            </el-button>
            <el-button size="mini" plain type="danger" icon="el-icon-suitcase" v-has="permissionBatchSetCollect"
                       @click="handleClickBatchCollect">设置收样员
            </el-button>
            <el-button size="mini" plain type="danger" icon="el-icon-edit" v-has="permissionBatchUpdateHos"
                       @click="handleClickBatchUpdateHos">批量修改医院
            </el-button>
            <el-button size="mini" plain type="success" icon="el-icon-printer" v-has="permissionBatchPrint"
                       @click="handleClickBatchPrint">批量打印
            </el-button>
            <el-button size="mini" plain type="success" icon="el-icon-finished" v-has="permissionBatchDownload"
                       @click="handleClickBatchDownload">批量下载
            </el-button>
            <!-- <el-button
              size="mini"
              plain
              type="success"
              icon="el-icon-upload"
              v-has="permissionBatchCreateResult"
              @click="handleClickBatchCreateResult()"
              >批量生成结果</el-button
            > -->
            <el-button size="mini" plain type="info" icon="el-icon-folder" v-has="permissionExport"
                       @click="handleClickExport(0)">导出
            </el-button>
            <el-button size="mini" plain type="info" icon="el-icon-folder-opened" v-has="permissionExport"
                       @click="handleClickExport(1)">合并导出
            </el-button>
            <el-button size="mini" plain type="info" icon="el-icon-folder" v-has="permissionExportPreCode"
                       @click="handleClickExportPreCode()">导出预制码
            </el-button>
            <el-button size="mini" plain type="info" icon="el-icon-folder" v-has="permissionPrintCode"
                       @click="handleClickPrintCode()">打印条码
            </el-button>
          </div>
        </div>
      </el-col>
    </el-row>

    <el-row ref="tableRow">
      <!-- 列表 -->
      <el-table
          :data="reportList"
          @selection-change="changeSelect"
          @row-dblclick="handleClickPrint"
          highlight-current-row
          :height="maxHeight"
          v-loading="listLoading"
          element-loading-text="数据加载中，请稍后..."
          empty-text="对不起，没有找到相关数据！"
          fit
          style="width: 100%"
      >
        <el-table-column type="selection" width="50" align="center"></el-table-column>
        <el-table-column type="index" width="50" align="center" label="序号"></el-table-column>
        <el-table-column prop="reportBeginTime" label="送检时间" width="87"></el-table-column>
        <el-table-column prop="reportCode" label="编号" width="130">
          <template slot-scope="scope">
            <span v-if="scope.row.reportCode">
              {{ scope.row.reportCode }}
              <el-tooltip class="item" effect="dark" content="复制" placement="top">
                <el-button
                    class="copy_reportCode"
                    size="mini"
                    icon="el-icon-document-copy"
                    circle
                    plain
                    id="copyBtn"
                    :data-clipboard-text="scope.row.reportCode"
                    @click="copyReportCode()"
                ></el-button>
              </el-tooltip>
            </span>
          </template>
        </el-table-column>
        <!--<el-table-column prop="searchCode" label="查询号"></el-table-column>-->
        <el-table-column width="150" align="center" label="姓名-性别-年龄">
          <template slot-scope="scope">
            <div>{{ scope.row.patientName }} - {{ formatSex(scope.row.patientSex) }} -
              <span v-if="scope.row.patientAge"> {{ scope.row.patientAge }}岁</span>
              <span v-if="scope.row.patientMonth"> {{ scope.row.patientMonth }}月</span>
              <span v-if="scope.row.patientDay"> {{ scope.row.patientDay }}天</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column width="180" align="center" label="医院-科室-医生">
          <template slot-scope="scope">
            <span>{{ scope.row.hospitalName }} - {{ scope.row.officeName }} - {{ scope.row.doctorName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="institutionName" label="医检机构" width="120"></el-table-column>
        <el-table-column label="平台/医检条码号" width="130">
          <template slot-scope="scope">
            <span v-if="scope.row.myReportCode">
              {{ scope.row.myReportCode }}
              <el-tooltip class="item" effect="dark" content="复制" placement="top">
                <el-button
                    class="copy_myReportCode"
                    size="mini"
                    icon="el-icon-document-copy"
                    circle
                    plain
                    id="copyBtn"
                    :data-clipboard-text="scope.row.myReportCode"
                    @click="copyMyReportCode()"
                ></el-button>
              </el-tooltip>
            </span>
            <span v-if="scope.row.insReportCode">
              {{ scope.row.insReportCode }}
              <el-tooltip class="item" effect="dark" content="复制" placement="top">
                <el-button
                    class="copy_insReportCode"
                    size="mini"
                    icon="el-icon-document-copy"
                    circle
                    plain
                    id="copyBtn"
                    :data-clipboard-text="scope.row.insReportCode"
                    @click="copyInsReportCode()"
                ></el-button>
              </el-tooltip>
            </span>
          </template>
        </el-table-column>
        <!--  show-overflow-tooltip 当字符长度大于单元格宽度时 省略 -->
        <el-table-column width="230" label="送检项目">
          <template slot-scope="scope">
            <span>
              {{ scope.row.itemName }}
              <el-tooltip class="item" effect="dark" content="复制" placement="top">
                <el-button
                    class="copy_itemName"
                    size="mini"
                    icon="el-icon-document-copy"
                    circle
                    plain
                    id="copyBtn"
                    :data-clipboard-text="scope.row.itemName"
                    @click="copyitemName()"
                ></el-button>
              </el-tooltip>
            </span>
          </template>
        </el-table-column>
        <el-table-column width="90" align="center" label="检测/打印">
          <template slot-scope="scope">
            <span>
              <el-tag size="mini" :type="formatReportStateType(scope.row.reportState)">
                {{ formatReportState(scope.row.reportState) }}
              </el-tag>
              <el-tag size="mini" :type="formatPrintStateType(scope.row.printState)" effect="dark">
                {{ formatPrintState(scope.row.printState) }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <!--<el-table-column prop="reportState" label="检测状态" :formatter="formatReportState"></el-table-column>-->
        <!--<el-table-column prop="abnormalState" label="异常状态" :formatter="formatAbnormalState"></el-table-column>-->
        <el-table-column prop="reportEndTime" label="报告时间" width="87"></el-table-column>
        <el-table-column label="收样员" width="100" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.syUserName }}</span
            ><span v-if="scope.row.syUserLevel">({{ scope.row.syUserLevel }}级)</span>
          </template>
        </el-table-column>
        <el-table-column prop="createUserName" label="创建人" width="90"></el-table-column>
        <el-table-column prop="createDate" label="创建时间" width="90"></el-table-column>
        <el-table-column label="上机状态" width="80" align="center">
          <template slot-scope="scope">
            <span>{{ getTransmitState(scope.row.transmitState) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="条码打印" width="80" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.codePrintState === 2 ? '已打印' : '未打印' }}</span>
          </template>
        </el-table-column>
        <!--错位的问题，在操作前一个列要加上width-->
        <el-table-column prop="reportPrintTime" label="最新打印时间" width="87"></el-table-column>
        <el-table-column label="操作" width="180px" fixed="right" style="align-content: center">
          <template slot-scope="scope">
            <!--<el-button v-has="permissionCheck" @click="handleClickDetail(scope.row)" size="mini">查看</el-button>
            <el-button v-has="permissionEdit" @click="handleClickEditor(scope.row)" size="mini">编辑</el-button>
            <el-button v-has="permissionUpStatus" @click="handleIsDisable(scope.row)" size="mini">删除</el-button>-->
            <el-button v-has="permissionPrint" v-if="scope.row.reportState === 20" @click="handleClickPrint(scope.row)"
                       size="mini">打印
            </el-button>
            <el-button v-has="permissionDownload" v-if="scope.row.reportState === 20"
                       @click="handleClickDownload(scope.row)" size="mini">下载
            </el-button>
            <el-dropdown trigger="click" size="small">
              <el-button type="primary"><i class="fa fa-list-ul"></i>更多</el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-has="permissionCheck" @click.native="handleClickDetail(scope.row)">查看
                </el-dropdown-item>
                <el-dropdown-item v-has="permissionEdit" @click.native="handleClickEditor(scope.row)">编辑
                </el-dropdown-item>
                <el-dropdown-item v-has="permissionCollect" @click.native="handleClickCollect(scope.row)">收取
                </el-dropdown-item>
                <el-dropdown-item v-has="permissionDelivered" @click.native="handleClickDelivered(scope.row)">送达
                </el-dropdown-item>
                <el-dropdown-item v-has="permissionReceived" @click.native="handleClickReceived(scope.row)">确认收到
                </el-dropdown-item>
                <el-dropdown-item v-has="permissionAddItem" @click.native="handleClickAddItem(scope.row)">添加项目
                </el-dropdown-item>
                <el-dropdown-item v-has="permissionUpload" @click.native="handleClickUpload(scope.row)">上传结果
                </el-dropdown-item>
                <el-dropdown-item v-has="permissionHealthView" @click.native="handleClickPatientDetail(scope.row)">
                  查看病情
                </el-dropdown-item>
                <el-dropdown-item v-has="permissionHealthUpload" @click.native="handleClickHealthUpload(scope.row)">
                  上传病情
                </el-dropdown-item>
                <el-dropdown-item v-has="permissionLinkDoctor" @click.native="handleClickLinkDoctor(scope.row)">
                  联系医生
                </el-dropdown-item>
                <el-dropdown-item v-has="permissionHelp" v-if="scope.row.reportState === 20"
                                  @click.native="handleClickHelp(scope.row)">解读及指导
                </el-dropdown-item>
                <el-dropdown-item v-has="permissionViewSpecimen" v-if="scope.row.syUserId"
                                  @click.native="handleClickViewSpecimen(scope.row)">查看标本箱
                </el-dropdown-item>
                <el-dropdown-item v-has="permissionBack" @click.native="handleClickReAccept(scope.row)">重新接收
                </el-dropdown-item>
                <el-dropdown-item v-has="permissionBack" v-if="scope.row.reportState === 20"
                                  @click.native="handleClickBack(scope.row)">撤回结果
                </el-dropdown-item>
                <el-dropdown-item v-has="permissionFinanceRemark"
                                  @click.native="financeRemarkDialog(scope.row.reportId)"> 财务备注
                </el-dropdown-item>
                <el-dropdown-item v-has="permissionOperator" @click.native="handleOperator(scope.row)">操作记录
                </el-dropdown-item>
                <el-dropdown-item v-has="permissionUpStatus" v-if="scope.row.state === 1"
                                  @click.native="handleIsDisable(scope.row, -1)">删除
                </el-dropdown-item>
                <el-dropdown-item v-has="permissionResume" v-if="scope.row.state === -1"
                                  @click.native="handleIsDisable(scope.row, 1)">恢复
                </el-dropdown-item>
                <el-dropdown-item v-has="permissionCancel" @click.native="handleCancel(scope.row)">取消
                </el-dropdown-item>

                <!--<el-dropdown-item v-has="permissionEdit" v-print="'#printDiv'" @click.native="handleClickPrint(scope.row)">打印</el-dropdown-item>
                <el-dropdown-item v-has="permissionEdit" @click.native="handleClickPrint(scope.row)">预览打印</el-dropdown-item>
                <el-dropdown-item v-has="permissionEdit" @click.native="handleClickDownload(scope.row)">下载</el-dropdown-item>
                <el-dropdown-item v-has="permissionUpStatus" @click.native="handleIsDisable(scope.row)">{{scope.row.state == 0? '启用' : '禁用'}}</el-dropdown-item>-->
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页工具条 -->
      <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="page.pageNo"
          :page-sizes="[20, 50, 100, 300, 500, 1000]"
          :page-size="page.pageSize"
          layout="total, sizes, jumper, next, pager, prev"
          :total="page.pageTotal"
      ></el-pagination>
    </el-row>

    <BatchAddReport ref="batchAddReport"></BatchAddReport>
    <BatchImport ref="BatchImport"></BatchImport>
    <BatchEditCollect ref="batchEditCollect"></BatchEditCollect>
    <uploadFile ref="uploadFile" @uploadFileList="getUploadFileList" accept="image,pdf" folder="report"></uploadFile>
    <uploadHealth ref="uploadHealth" :relationId="uploadHealthData.relationId"
                  :idCard="uploadHealthData.idCard"></uploadHealth>
    <viewPdf ref="viewPdf" :pdfUrl="pdfUrl" :isPrint="isPrint"></viewPdf>
    <linkTel ref="linkTel" :dataInfo="linkTelInfo"></linkTel>
    <addUserHelp ref="addUserHelp" :relationId="addHelpRelationId"></addUserHelp>
    <reportAddItem ref="reportAddItem" :reportId="addItemReportId" @reload="listReport"></reportAddItem>
    <CountDialog ref="countDialog" @counts="toExportPreCode"></CountDialog>

    <el-dialog title="财务备注" :visible.sync="financeRemarkVisible" center width="500px">
      <div style="position: relative">
        <el-button class="clear" type="danger" circle plain @click="confirmFinanceRemark(0)">清除</el-button>
        <el-input type="textarea" v-model="financeRemark" rows="7"></el-input>
      </div>
      <!-- <template > -->
      <template slot="footer">
        <el-button @click.native="financeRemarkVisible = false"> 取消</el-button>
        <el-button type="primary" @click.native="confirmFinanceRemark()"> 确定</el-button>
      </template>

      <!-- </template> -->
    </el-dialog>

    <el-dialog title="批量修改医院" :visible.sync="showBatchUpdateHos" center width="400px">
      <div style="text-align: center">
        <el-select clearable filterable v-model="selectedHospitalId" placeholder="请选择医院">
          <el-option v-for="item in hospitalList" :value="item.value" :label="item.label" :key="item.id"></el-option>
        </el-select>
      </div>

      <div slot="footer">
        <el-button type="primary" @click="confirmBatchUpdateHos"> 提交</el-button>
        <el-button @click="showBatchUpdateHos = false"> 取消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="操作记录" :visible.sync="operatorShow" center width="900px">
      <div style="text-align: center">
        <el-table :data="operatorList" highlight-current-row max-height="600">
          <el-table-column type="index" prop="operationType" label="操作类型" align="center" width="140">
            <template slot-scope="scope">
              <span>{{ operatorFilters(scope.row.operationType) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="operation" label="操作说明" align="center" width="200"></el-table-column>
          <el-table-column prop="remark" label="备注" align="center" width="200"></el-table-column>
          <el-table-column prop="createUserName" label="操作人员" align="center" width="100"></el-table-column>
          <el-table-column prop="createDate" label="操作时间" align="center" width="auto"></el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import * as message from '@/constants/message';
import * as constants from '@/constants/constants';
import uploadFile from '@/components/UploadFile';
import uploadHealth from '@/components/UploadHealth';
import viewPdf from '@/components/viewPdf';
import linkTel from '@/components/LinkTel';
import CountDialog from '@/components/CountDialog';
import addUserHelp from '@/components/AddUserHelp';
import reportAddItem from '@/components/ReportAddItem';
import InstitutionSelect from '@/components/InstitutionSelect';
import BatchAddReport from '@/components/BatchAddReport';
import BatchImport from '@/components/BatchImport';
import BatchEditCollect from '@/components/BatchEditCollect';
import {FORMAT_DATE_YYYY_MM_DD} from '@/constants/constants';
import {mapGetters, mapActions} from 'vuex';
import axios from 'axios';
import EquipApi from '@/api/equip/equip';
import InstitutionApi from '@/api/institution/institution';
import CollectApi from '@/api/collect/collect';
import HospitalApi from '@/api/institution/hospital';
import OfficeApi from '@/api/institution/office';
import ReportApi from '@/api/report/report';
import DoctorApi from '@/api/institution/doctor';
import {getStorage} from '@/utils/auth';
import Clipboard from 'clipboard';
import * as stn from '@/constants/storeName';
import fileDownload from "js-file-download";

export default {
  name: 'ReportManagement',
  inject: ['reload'], //注入局部刷新
  metaInfo: {
    meta: [
      {
        httpEquiv: 'Content-Security-Policy',
        content: 'upgrade-insecure-requests',
      },
    ],
  },
  data() {
    return {
      reportList: [],
      reportDataList: [],
      selectIds: [],
      selectReportList: [],
      userInfo: {},
      userRelation: {},
      userRole: '',
      pdfUrl: '',
      linkTelInfo: {},
      reportId: 0,
      addHelpRelationId: null,
      addItemReportId: null,
      isPrint: false,
      listLoading: true, // 列表加载loading
      pageLoading: false, // 页面加载loading
      reportStateType: '', //状态标签默认样式
      filters: {
        reportId: '',
        queryCode: '',
        searchCode: '',
        patientQuery: '',
        userId: '', //收样员id
        hospitalId: '',
        officeId: '',
        doctorId: '',
        institutionId: '',
        itemName: '',
        reportState: '',
        resultState: '',
        abnormalState: '',
        printState: '',
        state: '1',
        applyId: '',
        date: [],
      },
      maxHeight: 500,
      uploadAccept: 0, // 上传的文件类型 0.all 1.pdf 2.img 3.video 4.excel
      uploadData: {
        reportId: '',
        reportIdList: [],
        uploadFiles: [],
      },
      uploadHealthData: {
        relationId: null,
        idCard: '',
      },
      page: {
        pageNo: 1,
        pageTotal: 0,
        pageSize: 20,
      },
      collectList: [],
      hospitalList: [],
      officeList: [],
      doctorList: [],
      institutionList: [],
      reviewStatue: [
        {label: '未收取', value: 0},
        {label: '已收取', value: 5},
        {label: '已送达', value: 10},
        {label: '检测中', value: 15},
        {label: '已出结果', value: 20},
        {label: '取消中', value: 18},
        {label: '已取消', value: 19},
      ],
      abnormalStatue: [
        {label: '条码号异常', value: 1},
        {label: '姓名/身份证异常', value: 2},
        {label: '年龄/性别异常', value: 3},
        {label: '多条结果', value: 4},
        // { label: '结果未出', value: 5 },
        // { label: '结果时间太久，需要去对于官网查询', value: 6 },
        {label: '报告单结果未全出', value: 7},
        {label: '认证错误', value: 8},
      ],
      agenciesStatue: [
        {label: '未打印', value: 0},
        {label: '已打印', value: 1},
      ],
      resultStatue: [
        {label: '检测中', value: 0},
        {label: '已出结果', value: 1},
      ],

      permissionAdd: 'SYSTEM_MANAGER_REPORT_INFO_LIST_ADD',
      permissionCheck: 'SYSTEM_MANAGER_REPORT_INFO_LIST_SEE',
      permissionBack: 'SYSTEM_MANAGER_REPORT_INFO_LIST_BACK',
      permissionEdit: 'SYSTEM_MANAGER_REPORT_INFO_LIST_EDIT',
      permissionUpload: 'SYSTEM_MANAGER_REPORT_INFO_LIST_UPLOAD',
      permissionHealthUpload: 'SYSTEM_MANAGER_REPORT_INFO_LIST_HEALTH_UPLOAD',
      permissionHealthView: 'SYSTEM_MANAGER_REPORT_INFO_LIST_HEALTH_VIEW',
      permissionViewSpecimen: 'SYSTEM_MANAGER_REPORT_INFO_LIST_VIEW_SPECIMEN',
      permissionUpStatus: 'SYSTEM_MANAGER_REPORT_INFO_LIST_DELETE',
      permissionLinkDoctor: 'SYSTEM_MANAGER_REPORT_INFO_LIST_LINK_DOCTOR',
      permissionHelp: 'SYSTEM_MANAGER_REPORT_INFO_LIST_HELP',
      permissionResume: 'SYSTEM_MANAGER_REPORT_INFO_LIST_RESUME',
      permissionPrint: 'SYSTEM_MANAGER_REPORT_INFO_LIST_PRINT',
      permissionBatchPrint: 'SYSTEM_MANAGER_REPORT_INFO_LIST_BATCH_PRINT',
      permissionBatchDownload: 'SYSTEM_MANAGER_REPORT_INFO_LIST_BATCH_DOWNLOAD',
      permissionBatchSetCollect: 'SYSTEM_MANAGER_REPORT_INFO_LIST_BATCH_SET_COLLECT',
      permissionBatchUpdateHos: 'SYSTEM_MANAGER_REPORT_INFO_LIST_BATCH_UPDATE_HOSPITAL',
      permissionBatchCreateResult: 'SYSTEM_MANAGER_REPORT_INFO_LIST_BATCH_CREATE_RESULT',
      permissionRefreshItem: 'SYSTEM_MANAGER_REPORT_INFO_LIST_REFRESH_ITEM',
      permissionMergeUpload: 'SYSTEM_MANAGER_REPORT_INFO_LIST_MERGE_UPLOAD',
      permissionExportPreCode: 'SYSTEM_MANAGER_REPORT_INFO_LIST_EXPORT_PRECODE',
      permissionPrintCode: 'SYSTEM_MANAGER_REPORT_INFO_LIST_PRINT_CODE',
      permissionDelivered: 'SYSTEM_MANAGER_REPORT_INFO_LIST_DELIVERED',
      permissionAddItem: 'SYSTEM_MANAGER_REPORT_INFO_LIST_ADD_ITEM',
      permissionReceived: 'SYSTEM_MANAGER_REPORT_INFO_LIST_RECEIVED',
      permissionCollect: 'SYSTEM_MANAGER_REPORT_INFO_LIST_COLLECT',
      permissionDownload: 'SYSTEM_MANAGER_REPORT_INFO_LIST_DOWNLOAD',
      permissionExport: 'SYSTEM_MANAGER_REPORT_INFO_LIST_EXPORT',
      permissionFinanceRemark: 'SYSTEM_MANAGER_REPORT_INFO_LIST_FINANCE_REMARK',
      permissionCancel: 'SYSTEM_MANAGER_REPORT_INFO_LIST_CANCEL',
      permissionOperator: 'SYSTEM_MANAGER_REPORT_INFO_LIST_OPERATOR',

      // 财务备注弹框
      financeRemarkVisible: false,
      financeRemarkReportId: '',
      financeRemark: '',
      excelData: {},
      allList: [],
      // 批量修改医院
      showBatchUpdateHos: false,
      selectedHospitalId: '',
      operatorShow: false,
      operatorList: [],
    };
  },
  computed: {
    ...mapGetters([]),
  },
  components: {
    // 引入组件
    uploadFile,
    InstitutionSelect,
    viewPdf,
    linkTel,
    addUserHelp,
    uploadHealth,
    reportAddItem,
    BatchEditCollect,
    BatchAddReport,
    CountDialog,
    BatchImport,
  },
  created() {
    this.init();
  },
  mounted() {
    // 为了实现手机端下拉框可以打字搜索
    this.$Utils.removeSelectReadOnly();
    //绑定事件
    window.addEventListener('keydown', this.keyDown);
  },
  activated() {
    if (this.$route.meta.keepAlive) {
      this.listReport();
    }
    let linkType = this.$route.query.linkType;
    if (linkType) {
      this.$refs.searchForm.resetFields();
      this.init();
    }
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  methods: {
    init() {
      let _this = this;
      _this.listLoading = true;
      _this.userInfo = getStorage(stn.USER_INFO);
      _this.userRelation = getStorage(stn.USER_RELATION);
      // 根据用户角色，设置定好的查询条件
      if (_this.userInfo) {
        _this.userRole = _this.userInfo.userRole;
        if (_this.userRole === 2) {
          // 医生用户 - 默认查询条件:已出结果未打印
          //this.filters.reportState = 20;
          //this.filters.resultState = 1;
          //this.filters.printState = 0;
          _this.listInstitution();
          // 如果是医生用户，默认查询与之关联的医院信息
          _this.filters.hospitalId = _this.userRelation.hospitalId;
          _this.listOffice();
        } else if (_this.userRole === 3) {
          // 医检用户 - 默认查询条件：检测中
          _this.filters.resultState = 0;
          //this.filters.reportState = 10;
          //this.filters.reportStateLess = 20;
          _this.listHospital();
        } else {
          _this.listInstitution();
          _this.listCollect();
          _this.listHospital();
        }
      }
      _this.initDate();
      // 从首页跳过来的
      let linkType = _this.$route.query.linkType;
      if (linkType) {
        if (linkType === 1) {
          // 未打印报告单
          _this.filters.reportState = 20;
          _this.filters.printState = 0;
        } else if (linkType === 2) {
          // 今日新增报告单
          let begin = new Date();
          begin.setHours(0);
          begin.setMinutes(0);
          begin.setSeconds(0);
          let end = new Date();
          end.setHours(23);
          end.setMinutes(59);
          end.setSeconds(59);
          _this.filters.date = [begin, end];
          _this.filters.reportState = '';
          _this.filters.printState = '';
          _this.filters.resultState = '';
        } else if (linkType === 3) {
          // 待处理报告单（医检）
          //this.filters.reportState = 10;
          //this.filters.reportStateLess = 20;
          _this.filters.resultState = 0;
        }
      }
      // 从请求帮助列表跳转过来
      /*if (this.$route.query.reportId){
        this.filters.reportId = this.$route.query.reportId
      }*/

      _this.listReport();
      _this.getTableHeight();
    },
    getTransmitState(state) {
      switch (state) {
        case 0:
          return '待接收';
        case 4:
          return '接收失败';
        case 5:
          return '已接收';
        case 10:
          return '上机成功';
        case 14:
          return '上机失败';
        case 15:
          return '再次上机';
        case 19:
          return '已取消';
        case 20:
          return '已完成';
      }
    },
    operatorFilters(state) {
      switch (state) {
        case 1:
          return '编辑报告单';
        case 2:
          return '合并报告单';
        case 3:
          return '修改报告单状态';
        case 4:
          return '添加报告单项目';
        case 5:
          return '新增/补充上传报告单结果';
        case 6:
          return '当对接医检项目接收后，需要重新数据，重新接受';
        case 7:
          return '删除/恢复报告单';
      }
    },
    getTableHeight() {
      this.$nextTick(function () {
        this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        window.onresize = () => {
          this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        };
      });
    },
    cancelReadOnly(onOff) {
      this.$nextTick(() => {
        if (!onOff) {
          const {select} = this.$refs;
          const input = select.$el.querySelector('.el-input__inner');
          input.removeAttribute('readonly');
        }
      });
    },
    initDate() {
      let begin = new Date();
      begin.setHours(0);
      begin.setMinutes(0);
      begin.setSeconds(0);
      begin.setMonth(begin.getMonth() - 1);
      let end = new Date();
      end.setHours(23);
      end.setMinutes(59);
      end.setSeconds(59);
      this.filters.date = [begin, end];
    },
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.initDate();
      this.onSearch();
    },
    /**
     * 复制项目名称
     */
    copyitemName() {
      var clipboard = new Clipboard('.copy_itemName');
      clipboard.on('success', (e) => {
        this.$Utils.messageSuccess('复制成功');
        // 释放内存
        clipboard.destroy();
      });
      clipboard.on('error', (e) => {
        // 不支持复制
        this.$Utils.messageError('该浏览器不支持自动复制');
        // 释放内存
        clipboard.destroy();
      });
    },
    /**
     * 复制平台条码号
     */
    copyMyReportCode() {
      var clipboard = new Clipboard('.copy_myReportCode');
      clipboard.on('success', (e) => {
        this.$Utils.messageSuccess('复制成功');
        // 释放内存
        clipboard.destroy();
      });
      clipboard.on('error', (e) => {
        // 不支持复制
        this.$Utils.messageError('该浏览器不支持自动复制');
        // 释放内存
        clipboard.destroy();
      });
    },
    /**
     * 复制医检条码号
     */
    copyInsReportCode() {
      var clipboard = new Clipboard('.copy_insReportCode');
      clipboard.on('success', (e) => {
        this.$Utils.messageSuccess('复制成功');
        // 释放内存
        clipboard.destroy();
      });
      clipboard.on('error', (e) => {
        // 不支持复制
        this.$Utils.messageError('该浏览器不支持自动复制');
        // 释放内存
        clipboard.destroy();
      });
    },
    /**
     * 复制编号
     */
    copyReportCode() {
      var clipboard = new Clipboard('.copy_reportCode');
      clipboard.on('success', (e) => {
        this.$Utils.messageSuccess('复制成功');
        // 释放内存
        clipboard.destroy();
      });
      clipboard.on('error', (e) => {
        // 不支持复制
        this.$Utils.messageError('该浏览器不支持自动复制');
        // 释放内存
        clipboard.destroy();
      });
    },
    formatSex(cellValue) {
      if (cellValue === 1) {
        return '男';
      } else if (cellValue === 2) {
        return '女';
      }
    },
    formatAbnormalState(row, column, cellValue) {
      if (cellValue === 1) {
        return '条码号异常';
      } else if (cellValue === 2) {
        return '姓名/身份证异常';
      } else if (cellValue === 3) {
        return '年龄/性别异常';
      } else if (cellValue === 4) {
        return '多条结果';
      }
    },
    formatPrintState(cellValue) {
      if (cellValue === 0) {
        return '未打印';
      } else if (cellValue === 1) {
        return '已打印';
      }
    },
    formatPrintStateType(cellValue) {
      if (cellValue === 0) {
        return 'info';
      } else if (cellValue === 1) {
        return 'success';
      }
    },
    formatReportState(cellValue) {
      if (cellValue === 0) {
        return '未收取';
      } else if (cellValue === 5) {
        return '已收取';
      } else if (cellValue === 10) {
        return '已送达';
      } else if (cellValue === 12) {
        return '已收到';
      } else if (cellValue === 15) {
        return '检测中';
      } else if (cellValue === 17) {
        return '已出部分结果';
      } else if (cellValue === 18) {
        return '取消中';
      } else if (cellValue === 19) {
        return '已取消';
      } else if (cellValue === 20) {
        return '已出结果';
      }
    },
    formatReportStateType(cellValue) {
      if (cellValue === 0) {
        return 'danger';
      } else if (cellValue === 5) {
        return 'success';
      } else if (cellValue === 10) {
        return '';
      } else if (cellValue === 12) {
        return '';
      } else if (cellValue === 15) {
        return 'warning';
      } else if (cellValue === 17) {
        return 'info';
      } else if (cellValue === 18) {
        return 'info';
      } else if (cellValue === 19) {
        return 'info';
      } else if (cellValue === 20) {
        return 'success';
      }
    },
    formatState(row, column, cellValue) {
      if (cellValue === -1) {
        return '删除';
      } else if (cellValue === 0) {
        return '禁用';
      } else if (cellValue === 1) {
        return '启用';
      } else if (cellValue == 2) {
        return '待审核';
      }
    },
    formatDate(row, column, cellValue) {
      let _this = this;
      return _this.$Utils.formatDate(cellValue, FORMAT_DATE_YYYY_MM_DD);
    },
    formatDateTime(row, column, cellValue) {
      let _this = this;
      return _this.$Utils.formatDate(cellValue, 'yyyy-MM-dd hh:mm:ss');
    },
    listCollect() {
      let _this = this;
      _this.loadingIns = true;
      let cond = {roleId: 4}; // 暂不传入任何参数
      // collectNameList--/admin/listAdmin  获取收样员名字列表
      CollectApi.listCollectUserName(cond).then((res) => {
        setTimeout(() => {
          _this.loadingIns = false;
          _this.collectList = res.data.map((item) => {
            return {
              // roleId:4,
              value: item.userId,
              label: item.userName,
            };
          });
        }, 200);
      });
    },
    listHospital() {
      let _this = this;
      _this.loadingIns = true;
      let cond = {
        hospitalType: 1,
      };
      HospitalApi.getHospitalNameList(cond).then((res) => {
        setTimeout(() => {
          _this.loadingIns = false;
          _this.hospitalList = res.data.map((item) => {
            return {
              value: item.hospitalId,
              label: item.hospitalName,
            };
          });
        }, 200);
      });
    },
    listOffice() {
      let _this = this;
      _this.loadingIns = true;
      _this.officeList = [];
      _this.filters.officeId = '';
      _this.doctorList = [];
      _this.filters.doctorId = '';
      let cond = {
        hospitalId: _this.filters.hospitalId,
      };
      OfficeApi.getOfficeNames(cond)
          .then((res) => {
            setTimeout(() => {
              _this.loadingIns = false;
              _this.officeList = res.data.map((item) => {
                return {
                  value: item.officeId,
                  label: item.officeName,
                };
              });
            }, 200);
          })
          .catch((error) => {
            _this.officeList = [];
            console.error(error);
          });
    },
    listDoctor() {
      let _this = this;
      _this.loadingIns = true;
      _this.doctorList = [];
      _this.filters.doctorId = '';
      let cond = {
        hospitalId: _this.filters.hospitalId,
        officeId: _this.filters.officeId,
      };
      DoctorApi.getDoctorNames(cond)
          .then((res) => {
            setTimeout(() => {
              _this.loadingIns = false;
              _this.doctorList = res.data.map((item) => {
                return {
                  value: item.doctorId,
                  label: item.doctorName,
                };
              });
            }, 200);
          })
          .catch((error) => {
            _this.doctorList = [];
            console.error(error);
          });
    },
    listInstitution(query) {
      let _this = this;
      let institutionName = !query || typeof query !== 'string' ? '' : query;
      _this.loadingIns = true;
      InstitutionApi.selectInsByUser(institutionName)
          .then((res) => {
            setTimeout(() => {
              _this.loadingIns = false;
              _this.institutionList = res.data.map((item) => {
                return {
                  value: item.institutionId,
                  label: item.institutionName,
                };
              });
            }, 200);
          })
          .catch((error) => {
            _this.institutionList = [];
            console.error(error);
          });
    },
    handleSizeChange(size) {
      let _this = this;
      _this.page.pageSize = size;
      _this.listReport();
    },
    handleCurrentChange(val) {
      let _this = this;
      _this.page.pageNo = val;
      _this.listReport();
    },
    handleClickEditor(row) {
      let _this = this;
      _this.$router.push({
        path: row.reportSource === 1 ? '/report/reportEdit' : '/report/newReportEdit',
        query: {id: row.reportId},
      });
    },
    handleClickHealthUpload(row) {
      // console.log("进入方法")
      let _this = this;
      _this.uploadHealthData.relationId = row.reportId;
      _this.uploadHealthData.idCard = row.patientCard;

      // 传两个值 报告单id，和0
      _this.$refs.uploadHealth.handleCreate();
    },
    handleClickPrintCode() {
      let _this = this;
      if (_this.selectIds.length > 0) {
        this.$confirm('是否批量打印' + _this.selectIds.length + '个报告单的条码号？', message.TITLE_PROMPT, {}).then(() => {
          ReportApi.printReportCode({
            reportIds: _this.selectIds.toString(),
          }).then((res) => {
            _this.listReport();
          });
        });
      } else {
        _this.$notify.error({
          title: message.TITLE_ERROR,
          message: '请选择你要打印的报告单！',
        });
      }
    },
    handleClickUpload(row) {
      let _this = this;
      _this.uploadAccept = 1;
      _this.uploadData.reportId = row.reportId;
      _this.uploadData.reportIdList = [];
      _this.$refs.uploadFile.handleCreate();
    },
    handleClickMergeUpload() {
      let _this = this;
      if (_this.selectReportList.length < 2) {
        _this.$Utils.messageError('请至少选择2个报告单进行合并');
        return;
      }
      //let originCode = _this.selectReportList[0].originCode;
      let isCan = true;
      /*_this.selectReportList.forEach(item => {
        if (item.originCode !== originCode) {
          _this.$Utils.messageError("请选择相同患者的报告单进行合并上传");
          isCan = false;
          return;
        }
      });*/
      if (isCan) {
        this.$confirm('确定合并报告单并上传结果吗？', message.TITLE_PROMPT, {}).then(() => {
          _this.uploadAccept = 1;
          _this.uploadData.reportId = '';
          _this.uploadData.reportIdList = this.selectIds;
          _this.$refs.uploadFile.handleCreate();
        });
      }
    },
    handleClickCollect(row) {
      let _this = this;
      _this.$confirm('是否收取该标本', message.TITLE_PROMPT, {}).then(() => {
        ReportApi.updateReportState({
          reportId: row.reportId,
          reportState: 5,
        })
            .then((res) => {
              //this.reportList.splice(index,1)
              _this.listReport();
            })
            .catch((error) => {
              console.error(error);
            });
      });
    },
    handleClickDelivered(row) {
      let _this = this;
      _this.$confirm('是否送达该标本', message.TITLE_PROMPT, {}).then(() => {
        ReportApi.updateReportState({
          reportId: row.reportId,
          reportState: 10,
        })
            .then((res) => {
              //this.reportList.splice(index,1)
              _this.listReport();
            })
            .catch((error) => {
              console.error(error);
            });
      });
    },
    handleClickReceived(row) {
      let _this = this;
      _this.$confirm('是否确认已收到该标本', message.TITLE_PROMPT, {}).then(() => {
        ReportApi.updateReportState({
          reportId: row.reportId,
          reportState: 12,
        })
            .then((res) => {
              //this.reportList.splice(index,1)
              _this.listReport();
            })
            .catch((error) => {
              console.error(error);
            });
      });
    },
    handleClickAddItem(row) {
      this.addItemReportId = row.reportId;
      this.$refs.reportAddItem.handleCreate();
    },
    handleClickViewSpecimen(row) {
      let _this = this;
      if (!row.syUserId) {
        _this.$notify.error({
          title: message.TITLE_PROMPT,
          message: '该报告暂未关联收样员，请先设置收样员',
        });
        return;
      }
      // 查询该收样员是否绑定标本箱
      EquipApi.getIdBySyUserId({
        syUserId: row.syUserId,
      }).then((res) => {
        if (res.data) {
          _this.$router.push({
            path: '/equip/boxDetail',
            query: {id: res.data, syUserId: row.syUserId},
          });
        } else {
          _this.$Utils.notifyError('未找到对应的标本箱');
        }
      });
    },
    // 联系医生
    handleClickLinkDoctor(row) {
      let _this = this;
      ReportApi.getReportLink({
        reportId: row.reportId,
      }).then((res) => {
        if (res.data) {
          _this.linkTelInfo = res.data;
          _this.$refs.linkTel.handleCreate();
        } else {
          _this.$Utils.notifyError('报告单不存在');
        }
      });
    },
    handleClickHelp(row) {
      this.addHelpRelationId = row.reportId;
      this.$refs.addUserHelp.handleCreate();
    },
    // pdf上传
    getUploadFileList(val) {
      ////debugger
      let _this = this;
      if (!val) {
        _this.$Utils.messageError('请选择pdf上传');
        return;
      }
      _this.uploadData.uploadFiles = val;
      if (_this.uploadData.reportId) {
        ReportApi.addReportPdf(_this.uploadData)
            .then((res) => {
              _this.$Utils.notifySuccess();
              _this.listReport();
            })
            .catch((error) => {
              _this.$Utils.notifyError('上传失败，请稍后重试');
            });
      } else if (!_this.uploadData.reportId && _this.uploadData.reportIdList.length > 0) {
        ReportApi.addReportMerge(this.uploadData).then((res) => {
          _this.$Utils.notifySuccess();
          _this.listReport();
        });
      }
      //this.listReport()
    },
    changeSelect(val) {
      this.selectIds = [];
      for (let i = 0; i < val.length; i++) {
        this.selectIds.push(val[i].reportId);
      }
      this.selectReportList = val;
    },
    handleClickForPrint() {
      let _this = this;
      if (_this.isPrint) {
        _this
            .$confirm('是否已打印报告单结果？', message.TITLE_PROMPT, {
              cancelButtonText: '取消',
              confirmButtonText: '确定',
            })
            .then(() => {
              let param;
              if (_this.reportId > 0) {
                param = {reportId: _this.reportId};
              } else {
                if (_this.selectIds.length > 0) {
                  param = {reportIds: _this.selectIds.toString()};
                }
              }
              ReportApi.getReportPrint(param).then((res) => {
                // console.log("打印成功")
                _this.getReportUnprintCount();
              });
            });
      }
    },
    handleClickBatchPrint() {
      let _this = this;
      if (_this.selectIds.length > 0) {
        this.$confirm('是否批量打印' + _this.selectIds.length + '个报告单？', message.TITLE_PROMPT, {}).then(() => {
          ReportApi.getReportBatchPrint({
            reportIds: _this.selectIds.toString(),
          }).then((res) => {
            if (res.data) {
              _this.isPrint = true;
              _this.reportId = 0;
              _this.pdfUrl = res.data;
              this.$refs.viewPdf.handleCreate();
              //_this.$OpenUrl(res.data);
              //_this.getReportUnprintCount();
            } else {
              _this.$notify.error({
                title: message.TITLE_ERROR,
                message: '未上传报告单结果',
              });
            }
          });
        });
      } else {
        _this.$notify.error({
          title: message.TITLE_ERROR,
          message: '请选择你要打印的报告单！',
        });
      }
    },
    handleClickBatchCollect() {
      // 批量编辑收收样员
      let _this = this;
      if (_this.selectIds.length > 0) {
        _this.$refs.batchEditCollect.handleCreate(this.selectIds);
      } else {
        this.$message({
          message: '至少选择一条数据！',
          type: 'error',
        });
      }
    },
    handleClickBatchUpdateHos() {
      if (this.selectIds.length == 0) {
        this.$message.error('至少选择一项数据');
        return;
      }
      this.showBatchUpdateHos = true;
    },
    confirmBatchUpdateHos() {
      if (!this.selectedHospitalId) {
        this.$message.error('请选择医院');
        return;
      }
      this.$confirm('确定批量修改医院吗？', '提示', {}).then(() => {
        const params = {
          id: this.selectedHospitalId,
          ids: this.selectIds,
        };
        ReportApi.batchUpdateHos(params).then((res) => {
          this.$Utils.notifySuccess('修改成功');
          this.showBatchUpdateHos = false;
          this.listReport();
        });
      });
    },
    handleClickPrint(row) {
      //_this.$print(this.$refs.print123)   打印指定区域
      if (row.reportState != 20) {
        return;
      }
      let _this = this;
      ReportApi.getReport({reportId: row.reportId}).then((res) => {
        if (res.data.reportFileUrl) {
          _this.isPrint = true;
          _this.reportId = row.reportId;
          _this.pdfUrl = res.data.reportFileUrl;
          this.$refs.viewPdf.handleCreate();
        } else {
          _this.$notify.error({
            title: message.TITLE_ERROR,
            message: '未上传报告单结果',
          });
        }
      });
    },
    getReportUnprintCount() {
      ReportApi.getUnPrintReportCount({})
          .then((res) => {
            sessionStorage.setItem('unprintCount', res.data);
          })
          .catch((error) => {
          });
    },
    handleClickDownload(row) {
      console.log(row, "aaaaa")
      let _this = this;
      let url = process.env.BASE_API + constants.reportDown + '?reportId=' + row.reportId;
      axios
          .get(url, {
            //url: 接口地址
            responseType: `arraybuffer`, //一定要写
          })
          .then((res) => {
            if (res.status == 200) {
              let blob = new Blob([res.data], {
                //type: `application/msword` //word文档为msword,pdf文档为pdf
                type: `application/pdf`, //word文档为msword,pdf文档为pdf
              });
              let objectUrl = window.URL.createObjectURL(blob);
              let link = document.createElement('a');
              let fName = row.hospitalName + "-" + row.officeName + "-" + row.doctorName + "-" + row.patientName; //下载文件的名字
              link.href = objectUrl;
              //link.setAttribute("download", fName);
              link.download = fName;
              document.body.appendChild(link);
              link.click();
              document.body.removeChild(link); // 下载完成移除元素
              window.URL.revokeObjectURL(objectUrl); // 释放掉blob对象
            } else {
              _this.$notify.error({
                title: message.TITLE_ERROR,
                message: '下载失败',
              });
            }
          });
    },

    handleClickBatchDownload() {
      let _this = this;
      //let url = process.env.BASE_API+constants.reportBatchDown;
      if (_this.selectIds.length > 0) {
        this.$confirm('是否批量下载' + _this.selectIds.length + '个报告单？', message.TITLE_PROMPT, {}).then(() => {
          let ids = _this.selectIds.toString();
          _this.$Utils.downloadFiles(ids, constants.reportBatchDown);
        });
      } else {
        _this.$Utils.messageError('请选择你要下载的报告单！');
      }
    },
    handleClickReAccept(row) {
      let _this = this;
      _this.$confirm('是否需要医检单位重新接收标本信息？', message.TITLE_PROMPT, {}).then(() => {
        ReportApi.getReportReAccept({reportId: row.reportId}).then((res) => {
          _this.listReport();
        });
      });
    },
    handleClickBack(row) {
      let _this = this;
      _this.$confirm('是否撤回该报告单已上传的文件', message.TITLE_PROMPT, {}).then(() => {
        ReportApi.getReportback({reportId: row.reportId}).then((res) => {
          _this.listReport();
        });
      });
    },
    handleIsDisable(row, state) {
      let _this = this;
      this.$confirm('是否' + (state == -1 ? '删除' : '恢复') + '该报告单', message.TITLE_PROMPT, {}).then(() => {
        ReportApi.deleteReport({
          reportId: row.reportId,
          state: state,
        }).then((res) => {
          _this.listReport();
        });
      });
    },
    handleCancel(row) {
      ReportApi.cancelReport({
        reportId: row.reportId,
      }).then(() => {
        _this.listReport();
      });
    },
    handleClickAddBatch() {
      // 批量新增报告单 - 通过弹出框的形式
      let _this = this;
      _this.$refs.batchAddReport.handleCreate(this.selectIds);
      _this.$refs.batchAddReport.getUserRole(this.userRole);
    },
    // 批量导入
    handleBatchImport() {
      let _this = this;
      _this.$refs.BatchImport.clearTable();
      _this.$refs.BatchImport.handleCreate(this.selectIds);
      _this.$refs.BatchImport.getUserRole(this.userRole);
    },

    handleClickAdd(newVersion) {
      let _this = this;
      if (newVersion) {
        _this.$router.push('/report/newReportAdd');
      } else {
        _this.$router.push('/report/reportAdd');
      }
    },
    handleClickDetail(row) {
      let _this = this;
      _this.$router.push({
        path: '/report/reportDetail',
        query: {id: row.reportId},
      });
    },
    handleClickExportPreCode() {
      this.$refs.countDialog.handleCreate();
    },
    handleClickBatchCreateResult() {
      let _this = this;
      if (_this.selectIds.length > 0) {
        this.$confirm('是否批量生成' + _this.selectIds.length + '个报告单结果？', message.TITLE_PROMPT, {}).then(() => {
          _this.pageLoading = true;
          ReportApi.batchCreateResult({reportIdList: _this.selectIds}).then((res) => {
            if (res.status == 0) {
              _this.$Utils.notifySuccess();
              _this.onSearch();
            } else {
              _this.$notify.error({
                title: message.TITLE_ERROR,
                message: '生成失败，请重试',
              });
            }
            _this.pageLoading = false;
          });
        });
      } else {
        _this.$notify.error({
          title: message.TITLE_ERROR,
          message: '请选择你要生成结果的报告单！',
        });
      }
    },
    toExportPreCode(val) {
      // 导出预制码
      let _this = this;
      _this
          .$confirm('此操作将导出' + val + '条预制码, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
          .then(() => {
            _this.pageLoading = true;
            ReportApi.exportPreCode({counts: val}).then((res) => {
              if (res.data && res.data.length > 0) {
                let result = res.data;
                _this.pageLoading = false;
                _this.export2ExcelForPreCode(result);
                _this.$Utils.notifySuccess('已导出 ' + res.data.length + ' 条预制码');
              } else {
                _this.$notify.error({
                  title: message.TITLE_ERROR,
                  message: '未找到可导出的数据，请稍后再试',
                });
              }
            });
          })
          .catch(() => {
            console.error(error);
          });
    },

    handleClickPatientDetail(row) {
      // 查看患者病情
      let _this = this;
      _this.$router.push({
        path: '/report/patientHealthDetail',
        query: {id: row.reportId, type: 1},
      });
    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode === 13) {
        this.onSearch();
      }
    },
    onSearch() {
      this.listLoading = true;
      this.page.pageNo = 1;
      this.listReport();
    },
    listReport() {
      let _this = this;
      let cond = {
        pageNo: _this.page.pageNo,
        pageSize: _this.page.pageSize,
        queryCode: _this.filters.queryCode,
        searchCode: _this.filters.searchCode,
        itemName: _this.filters.itemName,
        syUserId: _this.filters.userId,
        hospitalId: _this.filters.hospitalId,
        officeId: _this.filters.officeId,
        doctorId: _this.filters.doctorId,
        applyId: _this.filters.applyId,
        institutionId: _this.filters.institutionId,
        //reportStateLess: _this.filters.reportStateLess,
        state: _this.filters.state,
        patientQuery: _this.$Utils.isNullStrict(_this.filters.patientQuery) ? null : _this.filters.patientQuery,
        printState: _this.$Utils.isNullStrict(_this.filters.printState) ? null : _this.filters.printState,
        reportState: _this.$Utils.isNullStrict(_this.filters.reportState) ? null : _this.filters.reportState,
        resultState: _this.$Utils.isNullStrict(_this.filters.resultState) ? null : _this.filters.resultState,
        abnormalState: _this.$Utils.isNullStrict(_this.filters.abnormalState) ? null : _this.filters.abnormalState,
      };
      if (this.filters.date && this.filters.date.length == 2) {
        cond.createDateBegin = this.$Utils.formatDate(this.filters.date[0], 'yyyy-MM-dd hh:mm:ss');
        cond.createDateEnd = this.$Utils.formatDate(this.filters.date[1], 'yyyy-MM-dd hh:mm:ss');
      }

      // 将查询条件缓存起来
      //setLocalStorage(stn.REPORT_MANAGEMENT_PARAM,cond)

      ReportApi.getReportsList(cond)
          .then((res) => {
            _this.listLoading = false;
            _this.reportList = res.data.list;
            _this.allList = res.data.list;
            _this.page.pageTotal = res.data.total;
          })
          .catch((error) => {
            _this.listLoading = false;
            console.error(error);
          });
    },
    sureDoctorClick() {
      _this.$refs.doctorForm.validate((valid) => {
        if (valid) {
          _this.$confirm(message.MSG_CONFIRM_SAVE_ALTER, message.TITLE_PROMPT, {}).then(() => {
            // //debugger
            if (_this.doctorForm.doctorId) {
              _this.alterDoctor();
            } else {
              _this.addDoctor();
            }
          });
        }
      });
    },
    alterDoctor() {
      let _this = this;
      DoctorApi.editDoctor(this.doctorForm).then((data) => {
        this.dialogVisible = false;
        _this.listReport();
        _this.$Utils.notifySuccess();
      });
    },
    addDoctor() {
      DoctorApi.addDoctor(this.doctorForm);
      let _this = this.then((data) => {
        this.dialogVisible = false;
        _this.listReport();
        _this.$Utils.notifySuccess();
      });
    },
    handleClickExport(groupBy) {
      let _this = this;
      this.$confirm('此操作将导出excel文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        _this.pageLoading = true;
        let cond = {
          groupBy: groupBy,
          queryCode: _this.filters.queryCode,
          searchCode: _this.filters.searchCode,
          itemName: _this.filters.itemName,
          applyId: _this.filters.applyId,
          hospitalId: _this.filters.hospitalId,
          officeId: _this.filters.officeId,
          doctorId: _this.filters.doctorId,
          institutionId: _this.filters.institutionId,
          patientQuery: _this.filters.patientQuery,
          printState: _this.filters.printState,
          reportState: _this.filters.reportState,
          resultState: _this.filters.resultState,
          abnormalState: _this.filters.abnormalState,
          state: _this.filters.state,
          pageNo: _this.page.pageNo,
          pageSize: _this.page.pageSize,
        };
        if (_this.filters.date && _this.filters.date.length === 2) {
          cond.createDateBegin = _this.$Utils.formatDate(this.filters.date[0], 'yyyy-MM-dd hh:mm:ss');
          cond.createDateEnd = _this.$Utils.formatDate(this.filters.date[1], 'yyyy-MM-dd hh:mm:ss');
        }
        ReportApi.getReportExport(cond).then((res) => {
          fileDownload(res, '报告单导出记录.xlsx');
        }).finally(() => {
          _this.pageLoading = false;
        });
      }).catch(() => {
        console.error(error);
      });
    },
    export2ExcelForPreCode(list) {
      let that = this;
      require.ensure([], () => {
        const {export_json_to_excel} = require('../../excel/Export2Excel'); //这里必须使用绝对路径
        const tHeader = ['预制码', '创建时间']; // 导出的表头名
        const filterVal = ['preCode', 'createDate']; // 导出的表头字段名
        const data = that.formatJson(filterVal, list);
        let currentTime = this.$Utils.formatDate(new Date(), 'yyyy-MM-dd');
        export_json_to_excel(tHeader, data, `重庆急救中心预制码_${currentTime}`); // 导出的表格名称，根据需要自己命名
      });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]));
    },
    financeRemarkDialog(id) {
      ReportApi.getFinanceRemark({reportId: id}).then((res) => {
        this.financeRemarkReportId = id;
        this.financeRemark = res.data;
        this.financeRemarkVisible = true;
      });
    },
    confirmFinanceRemark(type = 1) {
      let params = {
        reportId: this.financeRemarkReportId,
        remark: type ? this.financeRemark : '',
      };
      let tip = type ? '确认提交修改吗？' : '确认清除财务备注吗？';
      this.$confirm(tip, '提示', {}).then((res) => {
        ReportApi.financeRemark(params).then((res) => {
          this.financeRemarkVisible = false;
          this.$message.success('操作成功');
        });
      });
    },
    handleOperator(row) {
      let params = {
        reportId: row.reportId,
      };
      ReportApi.getOperatorList(params).then((res) => {
        if (res.status == 0) {
          this.operatorList = res.data;
          this.operatorShow = true;
        }
      });
    },
  },
  /*beforeRouteEnter(to,from,next){
    next(vm => {
      if (from.path == '/report/reportAdd' || from.path == '/report/reportEdit') {
        vm.init();
      }
    })
  }*/
};
</script>
<style scoped>
.print {
  width: 500px;
  height: 800px;
  /* show: false; */
}

#copyBtn {
  background: none;
  border: none;
}

#copyBtn:hover {
  background: none;
  border: none;
}

.clear {
  position: absolute;
  z-index: 999;
  top: -65px;
  width: 35px;
  height: 35px;
  padding: 3px;
  font-size: 13px !important;
}
</style>
<style lang="scss" src="@/assets/css/views/content.scss" scope></style>
